/**
 * @Title: AuthMechanismActivity.java
 * @Copyright: XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved
 * @Description: TODO<请描述此文件是做什么的>
 * @author: MeiYi
 * @data: 2016-1-5 上午11:24:06
 * @version: V1.0
 */

package artid.com.arttogo.activity;

import android.R.anim;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.android.volley.VolleyError;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import artid.com.arttogo.R;
import artid.com.arttogo.adapter.ArtCollectorsAdapter;
import artid.com.arttogo.adapter.Artist_Adapter;
import artid.com.arttogo.adapter.IndexesArtist_Adapter;
import artid.com.arttogo.bean.ArtCollectorsNewParser;
import artid.com.arttogo.bean.ArtistList;
import artid.com.arttogo.bean.SelectArtistcategory;
import artid.com.arttogo.bean.ShowPhoto;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.MySharedPreferences;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.VeDate;
import artid.com.arttogo.view.MyAdGallery;
import artid.com.arttogo.view.alphabeticalindex.IndexesMechanismBean;
import artid.com.arttogo.view.alphabeticalindex.MyLetterAlistView;
import artid.com.arttogo.view.alphabeticalindex.PinyinComparator_Mechanism;
import artid.com.arttogo.view.horizonlistview.NewartistArtistListParser;
import artid.com.arttogo.view.horizonlistview.NewartistArtistList_Adapter;
import artid.com.arttogo.view.pulllist.PullToRefreshLayout;
import artid.com.arttogo.view.MyGridView;

/**
 * 艺术家
 *
 * @author 熊彬
 * @data: 2016-1-5 上午11:24:06
 * @version: V1.0
 */
public class ArtCollectorsNewActivity extends BaseActivity implements
        OnClickListener {
    String TAG_CACHE_VIEW = "collecterView";
    String TAG_CACHE_CATE = "collecterCate";
    MySharedPreferences mSharePre;
    String strMallViewCache;//视图的缓存
    String strMallCateCache;//类目的缓存
    private Context mContext;
    private GridView mGridView;
    private ArtCollectorsAdapter adapter;
    private ImageView back;
    ImageView mimgMirrorCenter, mimgMirrorLeft;
    EditText meditSearch;
    View viewSearch;
    TextView textSearchTag, textcancel;
    Boolean isSearching = false;
    LinearLayout linearSearch;
    private int anmiSpeed = 400;
    View viewHide;
    // Boolean isRefsh = false;
    int pageIndex = 1, pagesize = 20;
    View mainView;
    View titleSearch;
    String strType = "1";//类别
    private ImageView popupwindowBtn;//排序按钮
    /**
     * 屏幕宽度
     */
    private int mScreenWidth;
    /**
     * 导航条目宽度
     */
    private int item_width;
    List<SelectArtistcategory> typeList;
    int endPosition = 0, beginPosition, currentFragmentIndex;
    ImageView mImageView;
    /**
     * 导航栏
     */
    private HorizontalScrollView mHorizontalScrollView;
    private LinearLayout recommendLL, mLinearLayout;
    String searchWord = "";
    View slideMain, viewPic;
    private RelativeLayout artCollectorsNew_RL;
    private MyAdGallery gallery; // 广告控件
    private MyGridView mListView;
    private PullToRefreshLayout mPullLayout;
    private boolean isRefreshed = false;// 是否刷新
    private int page = 1;
    private List<NewartistArtistListParser.NewartistArtistList_ArtistList> list;
    private List<NewartistArtistListParser.NewartistArtistList_ArtistList> more_list;
    private Artist_Adapter adapter_ListView;
    private PopupWindow window;
    // 请求类别
    // private String ac_id="1";
    // 请求排序
    private String orderid = "1";

    //字母索引
    private ListView mListView_Indexes;
    // 右侧A-Z字母列表
    private MyLetterAlistView letterListView;
    // dialog text
    private TextView overlay;
    // 估计是弹出dialog线程
    private OverlayThread overlayThread;
    //艺术家字母索引Adapter
    private IndexesArtist_Adapter adapter_IndexesArtist;
    private Handler handler;
    /**
     * 汉字转换成拼音的类
     */
    private List<IndexesMechanismBean> dateList;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator_Mechanism pinyinComparator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_horizontallistview);
        mContext = ArtCollectorsNewActivity.this;
        mSharePre = MySharedPreferences.getMySharedPreferences(mContext);
        mLinearLayout = (LinearLayout) findViewById(R.id.hsv_content);
        mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.hsv_view);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mScreenWidth = dm.widthPixels;
        item_width = (int) ((mScreenWidth / 5.0));
        mImageView = (ImageView) findViewById(R.id.img1);
        mImageView.getLayoutParams().width = item_width;
        titleSearch = (View) findViewById(R.id.collecter_serach);
        slideMain = (View) findViewById(R.id.artist_slideView);
        mainView = (View) findViewById(R.id.art_collect_view);
        mGridView = (GridView) findViewById(R.id.gridview);
        viewHide = (View) findViewById(R.id.view_hide_text);
        viewHide.setVisibility(View.GONE);
        viewHide.setOnClickListener(this);
        setSearchAnim();
        titleSearch.setOnClickListener(this);
        back = (ImageView) findViewById(R.id.title_back);
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                finish();
            }
        });
        recommendLL = (LinearLayout) findViewById(R.id.ArtCollectorsNew_RecommendLL);
        artCollectorsNew_RL = (RelativeLayout) findViewById(R.id.ArtCollectorsNew_RL);
        list = new ArrayList<NewartistArtistListParser.NewartistArtistList_ArtistList>();
        more_list = new ArrayList<NewartistArtistListParser.NewartistArtistList_ArtistList>();
        mListView = (MyGridView) findViewById(R.id.ListViewAndHorizonListview_ListView);
        mPullLayout = (PullToRefreshLayout) findViewById(R.id.refresh_layout);
        mPullLayout.setVisibility(View.INVISIBLE);
        popupwindowBtn = (ImageView) findViewById(R.id.ListViewAndHorizonListview_popupwindow);
        popupwindowBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                showPopwindow(mContext, v,
                        R.id.ListViewAndHorizonListview_popupwindow);
            }
        });
        mPullLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                // TODO Auto-generated method stub
                // 下拉刷新3
                page = 1;
                isRefreshed = true;
                getArtistListData();
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                // TODO Auto-generated method stub
                // pullToRefreshLayout.setBottomDismiss();
                // 上拉加载
                page++;
                getArtistListData();
            }
        });

        hint = (LinearLayout) findViewById(R.id.ll_hint);
        hint.setVisibility(View.GONE);
        ImageView imgblank = (ImageView) hint.findViewById(R.id.img_blank);
        imgblank.setImageResource(R.drawable.blank_artist);
        ((TextView) findViewById(R.id.text_blank)).setText("目前没有相关艺术家");
        handler = new Handler();
        overlayThread = new OverlayThread();
        letterListView = (MyLetterAlistView) findViewById(R.id.ArtCollectorsNew_MyLetterAlistView);
        letterListView.setVisibility(View.GONE);
        mListView_Indexes = (ListView) findViewById(R.id.ArtCollectorsNew_ListView);
        strMallCateCache = mSharePre.getValue(TAG_CACHE_CATE, "");
        if (!TextUtils.isEmpty(strMallCateCache)) {
            setCateDate(strMallCateCache);
        }
        strMallViewCache = mSharePre.getValue(TAG_CACHE_VIEW, "");
        if (!TextUtils.isEmpty(strMallViewCache)) {
            setMainDate(strMallViewCache);
        }
        requestCategoryList();
        getArtistListData();
    }

    private void initNav(List<SelectArtistcategory> list) {
        // String[] arrTag = {"简介","动态","在售","资讯"};
        mLinearLayout.removeAllViews();
        for (int i = 0; i < list.size(); i++) {
            RelativeLayout layout = new RelativeLayout(this);
            TextView view = new TextView(this);
            view.setText(list.get(i).getAname());
            view.setGravity(Gravity.CENTER_VERTICAL);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            params.addRule(RelativeLayout.CENTER_IN_PARENT);
            layout.addView(view, params);
            mLinearLayout.addView(layout, item_width,
                    Cache.dip2px(mContext, 40));
            layout.setOnClickListener(onClickType());
            layout.setTag(i);
        }
    }

    /**
     * 获取艺术家信息和作品信息。 页数 page 条数 pagesize 艺术家类别 ac_id 口令 token 排序规则 orderid
     * 默认的排序规则是降序 默认排序：1； 按人气从高到底：2 按加入顺序倒序：3 按作品数从多到少：4 按点赞数从高到底：5 按姓氏从A-Z：6
     */
    private static List<ImageView> dotViewList;
    ArrayList<String> imgFocusList, urlFocusList, idList, artistRankingTitleList;

    private void getArtistListData() {
        VolleyBasic.getInstance(this).post(
                Cache.Newartist_artistList,
                VolleyMap.getInstance().Newartist_artistList(page, pagesize,
                        strType, orderid), NewartistArtistListParser.class,
                new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        mPullLayout.loadmoreFinish(mPullLayout.SUCCEED);
                        mPullLayout.setVisibility(View.VISIBLE);
                        NewartistArtistListParser mBean = new NewartistArtistListParser();
                        mBean = (NewartistArtistListParser) vd.getData();
                        list = mBean.getArtistList();
                        if (isRefreshed == true) {
                            more_list.clear();
                            isRefreshed = false;
                        }
                        if (!list.isEmpty()) {
                            more_list.addAll(list);
                        }
                        /*
                         * //这里是显示有数据和无数据的布局 if(more_list!=null &&
						 * more_list.size()!=0){
						 * noDataLL.setVisibility(View.GONE); }else{
						 * noDataLL.setVisibility(View.VISIBLE); return; }
						 */
                        if (adapter_ListView == null) {
                            int length = (Integer.valueOf(NetUtils.getDisplayMetrics(ArtCollectorsNewActivity.this).get(NetUtils.DM_WIDTH)) - NetUtils.dip2px(mContext, 40)) / 3;

                            adapter_ListView = new Artist_Adapter(
                                    mContext, more_list, false, length);
                            mListView.setAdapter(adapter_ListView);

                        }
                        if (more_list != null && more_list.size() != 0) {
                            hint.setVisibility(View.GONE);
                        } else {
                            hint.setVisibility(View.VISIBLE);
                        }
                        adapter_ListView.notifyDataSetChanged();
                        Log.d("log", more_list.toString());

                        // 轮播加载
                        if (page == 1) {
                            LinearLayout dotLayout = (LinearLayout) findViewById(R.id.dotLayout);
                            dotLayout.setVisibility(View.GONE);
                            dotViewList = new ArrayList<ImageView>();
                            ImageView iv1 = (ImageView) findViewById(R.id.iv_carousel1);
                            imgFocusList = new ArrayList<String>();
                            urlFocusList = new ArrayList<String>();
                            idList = new ArrayList<String>();
                            artistRankingTitleList = new ArrayList<String>();
                            // viewPic = (View) findViewById(R.id.view_det_pic);
                            // viewPic.setVisibility(View.GONE);
                            // slideMain.setVisibility(View.VISIBLE);
                            gallery = (MyAdGallery) findViewById(R.id.myviewPager);
                            slideMain.setVisibility(View.VISIBLE);
                            String imgarrstr = "";
                            List<ShowPhoto> listPhotos = new ArrayList<ShowPhoto>();
                            ShowPhoto item = new ShowPhoto();
                            if (mBean.getBannerinfo() != null
                                    & !mBean.getBannerinfo().isEmpty()) {

                                for (NewartistArtistListParser.NewartistArtistList_Bannerinfo index : mBean
                                        .getBannerinfo()) {
                                    String imgString = index
                                            .getCarousel_imgurl();
                                    if (!TextUtils.isEmpty(imgString)
                                            & !imgString.contains("null")) {

                                        imgFocusList.add(imgString);
                                        urlFocusList.add(imgString);
                                        imgarrstr += (index
                                                .getCarousel_imgurl() + ",");
                                        // dotLayout.addView(iv1);
                                        dotViewList.add(iv1);
                                        idList.add(String.valueOf(index.getCarousel_id()));
                                        artistRankingTitleList.add(String.valueOf(index.getTitle()));
                                    }
                                }

                                String[] arrImg = imgarrstr.split(",");
                                gallery.setMyOnItemClickListener(new MyAdGallery.MyOnItemClickListener() {
                                    @Override
                                    public void onItemClick(int curIndex) {
                                        Intent intent = new Intent(mContext, ArtistRanking_Activity.class);
                                        intent.putExtra("id", idList.get(curIndex));
                                        intent.putExtra("title", artistRankingTitleList.get(curIndex));
                                        startActivity(intent);
                                    }
                                });
                                gallery.start(mContext, arrImg, null, 3000,
                                        dotViewList, R.drawable.point_pressed,
                                        R.drawable.point_unpressed);
                            }
                            //无轮播信息
                            else {
                                slideMain.setVisibility(View.GONE);
                            }
                        }
                        mainView.setVisibility(View.VISIBLE);
                        viewHide.setVisibility(View.GONE);

                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        mPullLayout.loadmoreFinish(mPullLayout.FAIL);
                        if (more_list != null && more_list.size() != 0) {
                            hint.setVisibility(View.GONE);
                        } else {
                            hint.setVisibility(View.VISIBLE);
                        }
						/*
						 * 这里是显示有数据和无数据的布局 if(more_list!=null &&
						 * more_list.size()!=0){
						 * noDataLL.setVisibility(View.GONE); }else{
						 * noDataLL.setVisibility(View.VISIBLE); return; }
						 */
                    }
                });
    }

    public void showPopwindow(final Context mContext, View v, int ViewId) {
        // 利用layoutInflater获得View
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.popupwindow_artistlistsort, null);
        // 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()
        window = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        window.setFocusable(true);
        window = new PopupWindow(view, WindowManager.LayoutParams.FILL_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT, false);
        // 设置可以获取焦点，否则弹出菜单中的EditText是无法获取输入的
        window.setFocusable(true);
        // 这句是为了防止弹出菜单获取焦点之后，点击activity的其他组件没有响应
        window.setBackgroundDrawable(new BitmapDrawable());
        // 设置popWindow的显示和消失动画
        window.setAnimationStyle(R.style.AnimBottom);
        // 防止虚拟软键盘被弹出菜单遮住
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        // 在底部显示
        window.showAtLocation(v.findViewById(ViewId), Gravity.BOTTOM, 0, 0);
        // 这里检验popWindow里的button是否可以点击
        TextView defaultBtn = (TextView) view
                .findViewById(R.id.popupwindow_artistlistsort_default);
        defaultBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 默认排序
                orderid = "1";
                page = 1;
                isRefreshed = true;
                getArtistListData();
                window.dismiss();
            }
        });
        TextView popularityBtn = (TextView) view
                .findViewById(R.id.popupwindow_artistlistsort_popularity);
        popularityBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 按人气从高到低
                orderid = "2";
                page = 1;
                isRefreshed = true;
                getArtistListData();
                window.dismiss();
            }
        });
        TextView joinBtn = (TextView) view
                .findViewById(R.id.popupwindow_artistlistsort_join);
        joinBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 按加入顺序倒序
                orderid = "3";
                page = 1;
                isRefreshed = true;
                getArtistListData();
                window.dismiss();
            }
        });
        TextView worksNumBtn = (TextView) view
                .findViewById(R.id.popupwindow_artistlistsort_worksNum);
        worksNumBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 按作品数从多到少
                orderid = "4";
                page = 1;
                isRefreshed = true;
                getArtistListData();
                window.dismiss();
            }
        });
        TextView giveTheThumbsUpBtn = (TextView) view
                .findViewById(R.id.popupwindow_artistlistsort_giveTheThumbsUp);
        giveTheThumbsUpBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 按点赞数从高到低
                orderid = "5";
                page = 1;
                isRefreshed = true;
                getArtistListData();
                window.dismiss();
            }
        });
        TextView surnameBtn = (TextView) view
                .findViewById(R.id.popupwindow_artistlistsort_surname);
        surnameBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 按姓氏从A-Z
                orderid = "6";
                page = 1;
                isRefreshed = true;
                getArtistListData();
                window.dismiss();
            }
        });
        TextView cancelBtn = (TextView) view
                .findViewById(R.id.popupwindow_artistlistsort_cancel);
        cancelBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // cancelBtn
                window.dismiss();
            }
        });
        // popWindow消失监听方法
        window.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss() {
                System.out.println("popWindow消失");
            }
        });
    }

    /**
     * 类别选择
     *
     * @return
     */
    View.OnClickListener onClickType() {
        View.OnClickListener listener = new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int position = (Integer) arg0.getTag();
                strType = typeList.get(position).getAid();
                Animation animation = new TranslateAnimation(endPosition,
                        position * item_width, 0, 0);

                beginPosition = position * item_width;

                currentFragmentIndex = position;
                if (animation != null) {
                    animation.setFillAfter(true);
                    animation.setDuration(0);
                    mImageView.startAnimation(animation);
                    mHorizontalScrollView.smoothScrollTo((currentFragmentIndex - 1) * item_width, 0);
                }
                if ("1".equals(strType)) {
                    //推荐
                    page = 1;
                    isRefreshed = true;
                    popupwindowBtn.setVisibility(View.VISIBLE);
                    getArtistListData();
                    recommendLL.setVisibility(View.VISIBLE);
                    artCollectorsNew_RL.setVisibility(View.GONE);
                } else {
                    //隐藏推荐UI
                    slideMain.setVisibility(View.GONE);
                    popupwindowBtn.setVisibility(View.GONE);
                    recommendLL.setVisibility(View.GONE);
                    artCollectorsNew_RL.setVisibility(View.VISIBLE);
                    getData();
                }
            }
        };
        return listener;

    }

    void inintType() {
        int position = 0;
        strType = typeList.get(position).getAid();

        Animation animation = new TranslateAnimation(endPosition, position
                * item_width, 0, 0);

        beginPosition = position * item_width;

        currentFragmentIndex = position;
        if (animation != null) {
            animation.setFillAfter(true);
            animation.setDuration(0);
            mImageView.startAnimation(animation);
            mHorizontalScrollView.smoothScrollTo((currentFragmentIndex - 1)
                    * item_width, 0);
        }
    }

    /**
     * 请求类别
     */
    private void requestCategoryList() {
        VolleyBasic.getInstance(ArtCollectorsNewActivity.this).post(
                Cache.selectArtistcategory,
                VolleyMap.getInstance().selectArtistcategory(),
                SelectArtistcategory.class, new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        System.out.println(vd.getJson());
                        // Toast.makeText(mContext, vd.getJson(), 2).show();
                        mSharePre.setValue(vd.getJson(), TAG_CACHE_CATE);
                        setCateDate(vd.getJson());


                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub

                    }
                });
    }

    void setCateDate(String json) {
        VolleyData vd = new VolleyData(json, SelectArtistcategory.class);
        final List<SelectArtistcategory> list = (List<SelectArtistcategory>) vd
                .getList();
        typeList = list;
        initNav(list);
    }
    // void reqData(final String keywork) {
    //
    // VolleyBasic.getInstance(ArtCollectorsNewActivity.this).post(
    // Cache.artistList,
    // VolleyMap.getInstance().artistList(strType,String.valueOf(pageIndex),
    // String.valueOf(pagesize), keywork,
    // AppUtil.getUser().getToken()), ArtistList.class,
    // new VolleyCallback() {
    //
    // @Override
    // public void onSuccess(VolleyData vd) {
    // // TODO Auto-generated method stub
    // mPullLayout.setVisibility(View.VISIBLE);
    // mPullLayout.loadmoreFinish(mPullLayout.SUCCEED);
    // List<ArtistList> list = (List<ArtistList>) vd
    // .getList();
    // hint.setVisibility(View.GONE);
    //
    // if (list.isEmpty()) {
    // if (pageIndex==1) {
    // list =new ArrayList<ArtistList>();
    // adapter.setdata(list,keywork);
    // hint.setVisibility(View.VISIBLE);
    // }
    // if (adapter.listdata.isEmpty()) {
    // hint.setVisibility(View.VISIBLE);
    // }
    // return;
    // }
    // if (pageIndex!=1) {
    // adapter.addlist(list);
    // setItemClick(adapter.listdata);
    //
    // return;
    // }
    // adapter = new ArtCollectorsAdapter(mContext);
    // adapter.setdata(list, keywork);
    // mGridView.setAdapter(adapter);
    // setItemClick(list);
    // mainView.setVisibility(View.VISIBLE);
    // viewHide.setVisibility(View.GONE);
    // }
    //
    // @Override
    // public void onError(VolleyError volleyError) {
    // // TODO Auto-generated method stub
    // mPullLayout.setVisibility(View.VISIBLE);
    // mPullLayout.loadmoreFinish(mPullLayout.FAIL);
    // }
    // });
    // }

    void setItemClick(final List<ArtistList> list) {
        mGridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                // ViewGroup vGroup =
                // (ViewGroup)mGridView.getChildAt(position);
                int y = (view.getTop());
                int x = (view.getLeft());
                Point point = new Point(x, y);
                // Intent intent = new Intent(
                // ArtCollectorsActivity.this,
                // CollecterActivity.class);
                Intent intent = new Intent(ArtCollectorsNewActivity.this,
                        CollecterActivity.class);
                intent.putExtra("xpoin", x);
                intent.putExtra("ypoin", y);
                intent.putExtra("id", list.get(position).getId());
                intent.putExtra("name", list.get(position).getRealname());
                startActivity(intent);
                overridePendingTransition(anim.fade_in, anim.fade_out);
            }
        });
    }

    void setSearchAnim() {
        textcancel = (TextView) findViewById(R.id.searchcancel);
        textcancel.setOnClickListener(this);
        textcancel.setVisibility(View.GONE);
        linearSearch = (LinearLayout) findViewById(R.id.linearLayout1);
        textSearchTag = (TextView) findViewById(R.id.textsearch);
        viewSearch = (View) findViewById(R.id.relasearch);
        viewSearch.setOnClickListener(this);
        mimgMirrorCenter = (ImageView) findViewById(R.id.imageView1);
        mimgMirrorLeft = (ImageView) findViewById(R.id.imageView2);
        meditSearch = (EditText) findViewById(R.id.editText1);
        meditSearch.setVisibility(View.GONE);
        meditSearch
                .setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    public boolean onEditorAction(TextView v, int actionId,
                                                  KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_SEARCH
                                || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                            pageIndex = 1;
                            strType = "1";
                            searchWord = meditSearch.getText().toString();
                            getArtistListData();
                            onClick(textcancel);
                            viewSearch.setVisibility(View.GONE);

                            inintType();
                            return true;
                        }
                        return false;
                    }
                });
        mimgMirrorLeft.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
            case R.id.relasearch:
                if (!isSearching) {
                    isSearching = true;
                    Animation translateAnimation2 = new TranslateAnimation(
                            VeDate.dip2px(mContext, 160), 0f, 0f, 0f);
                    translateAnimation2.setDuration(anmiSpeed);
                    mimgMirrorLeft.setAnimation(translateAnimation2);
                    mimgMirrorLeft.setVisibility(View.VISIBLE);
                    mimgMirrorCenter.setVisibility(View.GONE);
                    textSearchTag.setVisibility(View.GONE);
                    Animation scaleAnimation = new ScaleAnimation(1f, 0.8f, 1f, 1f,
                            1f, 1f);
                    scaleAnimation.setDuration(anmiSpeed);
                    scaleAnimation.setFillAfter(true);
                    scaleAnimation
                            .setAnimationListener(new Animation.AnimationListener() {
                                @Override
                                public void onAnimationStart(Animation arg0) {
                                    // TODO Auto-generated method stub

                                }

                                @Override
                                public void onAnimationRepeat(Animation arg0) {
                                    // TODO Auto-generated method stub

                                }

                                @Override
                                public void onAnimationEnd(Animation arg0) {
                                    // TODO Auto-generated method stub
                                    meditSearch.setVisibility(View.VISIBLE);
                                    textcancel.setVisibility(View.VISIBLE);
                                    meditSearch.requestFocus();
                                    viewHide.setVisibility(View.VISIBLE);
                                    openInput();

                                }
                            });
                    linearSearch.setAnimation(scaleAnimation);

                }
                break;

            case R.id.searchcancel:
                if (isSearching) {
                    isSearching = false;
                    // Animation translateAnimation2 = new
                    // TranslateAnimation(0f,VeDate.dip2px(getActivity(), 160),
                    // 0f, 0f);
                    // translateAnimation2.setDuration(500);
                    // mimgMirrorLeft.setAnimation(translateAnimation2);
                    mimgMirrorCenter.setVisibility(View.GONE);
                    mimgMirrorLeft.setVisibility(View.GONE);
                    meditSearch.setText("");
                    meditSearch.setVisibility(View.GONE);
                    textSearchTag.setVisibility(View.VISIBLE);
                    Animation scaleAnimation = new ScaleAnimation(0.8f, 1f, 1f, 1f,
                            1f, 1f);
                    scaleAnimation.setDuration(500);
                    scaleAnimation.setFillAfter(true);
                    linearSearch.setAnimation(scaleAnimation);
                    textcancel.setVisibility(View.GONE);
                    viewHide.setVisibility(View.GONE);
                    viewSearch.setVisibility(View.GONE);
                }
                break;
            case R.id.view_hide_text:
                closeInputMethod();
                break;
            case R.id.collecter_serach:
                Intent intent = new Intent(mContext, CollecterSearchActivity.class);
                startActivity(intent);

//			viewSearch.setVisibility(View.VISIBLE);
//			onClick(viewSearch);
                break;
            default:
                break;
        }
    }

    void openInput() {
        InputMethodManager m = (InputMethodManager) meditSearch.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    void closeInputMethod() {
        viewHide.setVisibility(View.GONE);
        try {
            InputMethodManager inputMethodManager = (InputMethodManager) mContext
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus()
                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
            // TODO: handle exception
            Log.d("", "关闭输入法异常");
        }
    }


    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    @SuppressLint("DefaultLocale")
    private List<IndexesMechanismBean> filledData(List<IndexesMechanismBean> date) {
        List<IndexesMechanismBean> mList = new ArrayList<IndexesMechanismBean>();
        for (int i = 0; i < date.size(); i++) {
            IndexesMechanismBean mBean = new IndexesMechanismBean();
            mBean.setName(date.get(i).getName());
            mBean.setId(date.get(i).getId());
            mBean.setSubscript(i);
            // 汉字转换成拼音
            String pinyin = getFirstSpell(date.get(i).getName());
            try {
                String sortString = pinyin.substring(0, 1).toUpperCase(Locale.CHINESE);
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    mBean.setSortLetters(sortString.toUpperCase());
                } else {
                    mBean.setSortLetters("#");
                }
            } catch (Exception e) {
                // TODO: handle exception
                //当遇到非法字符的时候会出现报错的问题，所以直接将他设置为#状态
                mBean.setSortLetters("#");
            }

            mList.add(mBean);
        }
        return mList;

    }

    // 右侧A-Z字母监听
    private class LetterListViewListener implements MyLetterAlistView.OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(final String s) {
            // 该字母首次出现的位置
            int position = adapter_IndexesArtist.getPositionForSection(s.charAt(0));
            if (position != -1) {
                mListView_Indexes.setSelection(position);
                overlay.setText(dateList.get(position).getSortLetters());
                overlay.setVisibility(View.VISIBLE);
                handler.removeCallbacks(overlayThread);
                // 延迟一秒后执行，让overlay为不可见
                handler.postDelayed(overlayThread, 500);
            }
        }
    }

    // 初始化汉语拼音首字母弹出提示框
    private void initOverlay() {
        LayoutInflater inflater = LayoutInflater.from(this);
        overlay = (TextView) inflater.inflate(R.layout.view_overlay, null);
        overlay.setVisibility(View.INVISIBLE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager windowManager = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overlay, lp);
    }

    // 设置overlay不可见
    private class OverlayThread implements Runnable {

        @Override
        public void run() {
            overlay.setVisibility(View.GONE);
        }

    }

    /**
     * 汉字转换为汉语拼音首字母
     *
     * @return 拼音
     */
    public static String getFirstSpell(String chinese) {
        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (char curchar : arr) {
            if (curchar > 128) {
                try {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(curchar, defaultFormat);
                    if (temp != null) {
                        pybf.append(temp[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(curchar);
            }
        }
        return pybf.toString().replaceAll("\\W", "").trim();
    }

    /**
     * 除推荐之外的数据
     */
    private void getData() {
        VolleyBasic.getInstance(this).post(Cache.capitalartistList,
                VolleyMap.getInstance().capitalartistList(strType),
                ArtCollectorsNewParser.class, new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        mSharePre.setValue(vd.getJson(), TAG_CACHE_VIEW);
                        setMainDate(vd.getJson());
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        dateList = new ArrayList<IndexesMechanismBean>();
                        adapter_IndexesArtist = new IndexesArtist_Adapter(mContext, dateList, null);
                        mListView_Indexes.setAdapter(adapter_IndexesArtist);
                        letterListView.setVisibility(View.GONE);
                        hint.setVisibility(View.VISIBLE);
                    }
                });
    }

    void setMainDate(String json) {
        VolleyData vd = new VolleyData(json, ArtCollectorsNewParser.class);
        List<ArtCollectorsNewParser> list = (List<ArtCollectorsNewParser>) vd.getList();
        dateList = new ArrayList<IndexesMechanismBean>();
        if (list != null && list.size() != 0) {
            hint.setVisibility(View.GONE);
            for (int i = 0; i < list.size(); i++) {
                IndexesMechanismBean bean1 = new IndexesMechanismBean();
                bean1.setId(list.get(i).getArtist_id());
                bean1.setName(list.get(i).getRealname());
                dateList.add(bean1);
            }
            dateList = filledData(dateList);
            // 根据拼音排序
            pinyinComparator = new PinyinComparator_Mechanism();
            Collections.sort(dateList, pinyinComparator);// 根据a-z进行排序源数据

            if (dateList != null && dateList.size() != 0) {
                List<String> letterAlistView_list = new ArrayList<String>();
                for (int i = 0; i < dateList.size(); i++) {
                    //先将数据添加到集合
                    letterAlistView_list.add(dateList.get(i).getSortLetters().toString());
                }
                //去重
                for (int i = 0; i < letterAlistView_list.size() - 1; i++) {
                    for (int j = letterAlistView_list.size() - 1; j > i; j--) {
                        if (letterAlistView_list.get(j).equals(letterAlistView_list.get(i))) {
                            letterAlistView_list.remove(j);
                        }
                    }
                }
                String[] letterAlistView_Data = new String[letterAlistView_list.size()];
                for (int i = 0; i < letterAlistView_list.size(); i++) {
                    letterAlistView_Data[i] = letterAlistView_list.get(i).toString();
                }
                letterListView.setData(letterAlistView_Data);
                letterListView.setVisibility(View.VISIBLE);
            }
            adapter_IndexesArtist = new IndexesArtist_Adapter(mContext, dateList, list);
            mListView_Indexes.setAdapter(adapter_IndexesArtist);
//							mListView.setOnItemClickListener(onItemClick);
            initOverlay();
            letterListView.setOnTouchingLetterChangedListener(new LetterListViewListener());
        } else {
            dateList = new ArrayList<IndexesMechanismBean>();
            adapter_IndexesArtist = new IndexesArtist_Adapter(mContext, dateList, null);
            mListView_Indexes.setAdapter(adapter_IndexesArtist);
            letterListView.setVisibility(View.GONE);
            hint.setVisibility(View.VISIBLE);
        }
    }
}
